package com.xx.controller;

import com.github.pagehelper.PageInfo;
import com.xx.entity.Employee;
import com.xx.entity.R;
import com.xx.enums.HttpEnum;
import com.xx.service.EmployeeService;
import com.xx.uril.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;

@RestController
@RequestMapping("/employees")
@CrossOrigin
public class EmployeeController {
    @Autowired
    EmployeeService employeeService;

    //查询全部员工
    @GetMapping
    public R<PageInfo<Employee>> getList(String empName,String jobTitle, Integer pageNum) {
        PageInfo<Employee> employeeList = employeeService.getList(empName, jobTitle,pageNum);
        return R.success(employeeList);
    }

    //获取书籍的详情
    @GetMapping("{employeeId}")
    public R<Employee> getBookInfo(@PathVariable("employeeId") Integer employeeId) {
        return R.success(employeeService.getEmployeeInfo(employeeId)) ;
    }

    //新增
    @PostMapping
    public R saveBook(@Valid Employee employee, MultipartFile bookImageFile, HttpServletRequest request){
        employee.setEmployeeId(1);
        String imPath;
        try {
            imPath = FileUtil.upload(request,bookImageFile);
            if(imPath != null){
                employee.setImagePath(imPath);
                System.out.println("图片上传成功!");
            }else {
                System.out.println("图片上传失败!");
            }
        }catch (IOException e){
            e.printStackTrace();
            System.out.println("图片上传失败!");
        }
        int count = employeeService.saveEmployee(employee);
        return count > 0 ? R.success("员工新增成功") :
                R.fail(HttpEnum.ERROR.getCode(),"员工新增失败");
    }


    //分页
    @GetMapping("/page")
    public R<PageInfo<Employee>> getPage(String empName,String jobTitle, Integer pageNum) {
        PageInfo<Employee> employeeList = employeeService.getList(empName, jobTitle,pageNum);
        return R.success(employeeList);
    }

    //修改
    @PutMapping
    public String updateEmployee(@RequestBody Employee employee){
        int count = employeeService.updateEmployee(employee);
        return count>0?"修改成功":"修改失败";
    }

    //删除
    @DeleteMapping("/{employeeId}")
    public String delEmployee(@PathVariable("employeeId") Integer employeeId){
        int count = employeeService.delEmployee(employeeId);
        return count>0?"删除成功":"删除失败";
    }
}
